package com.kehongborui.fliggy.interceptor;

import com.kehongborui.fliggy.annotation.LogAction;
import com.kehongborui.fliggy.entity.Log;
import com.kehongborui.fliggy.entity.User;
import com.kehongborui.fliggy.enums.LOGIN_USER;
import com.kehongborui.fliggy.queue.LogsQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-09-10
 */
public class LogInterceptor implements HandlerInterceptor {
    @Autowired
    private LogsQueue logsQueue;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("log_action_status", "失败");

        Object user = request.getSession().getAttribute(LOGIN_USER.USER.name());
        request.setAttribute("log_username", user == null ? "游客" : ((User)user).getUsername());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        request.setAttribute("log_action_status", "成功");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Log log = new Log();
        log.setEventTime(new Date());
        log.setResult(request.getAttribute("log_action_status").toString());
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = ((HandlerMethod) handler); // 强转为HandlerMethod
            LogAction action = handlerMethod.getMethodAnnotation(LogAction.class);
            log.setAction(action.action());
        }

        log.setUri(request.getRequestURI());
        log.setIp(request.getRemoteHost());

        log.setUsername((String)request.getAttribute("log_username"));
        log.setCode("########################");
        log.setContent("###############");
        logsQueue.push(log);
    }
}
